/*
 * @Description: user login
 * @Author: zhaokun
 * @Date: 2021-12-29 14:48:33
 * @LastEditTime: 2022-01-27 16:08:19
 * @FilePath: \user\api\internal\logic\loginLogic.go
 */
package logic

import (
	"context"
	"strings"
	"time"
	"user/api/internal/svc"
	"user/api/internal/types"
	nwError "user/common"
	"user/rpc/userservice"

	"github.com/golang-jwt/jwt"
	"github.com/tal-tech/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) LoginLogic {
	return LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

/**
 * @description:
 * @param LoginRequest req
 * @return {resp,err}
 */
func (l *LoginLogic) Login(req types.LoginRequest) (resp *types.LoginResponse, err error) {
	if len(strings.TrimSpace(req.Name)) == 0 || len(strings.TrimSpace(req.Password)) == 0 {
		return nil, nwError.NewDefaultError("登录信息不能为空")
	}
	userInfo, err := l.svcCtx.UserService.FindUser(l.ctx, &userservice.FindRequest{
		Where: "name=?",
		Param: []string{strings.TrimSpace(req.Name)},
	})

	if err != nil {
		l.Logger.Error(err.Error())
	}

	userCount, err := l.svcCtx.UserService.GetCount(l.ctx, &userservice.CountRequest{
		Where: "uniacid=?",
		Param: []string{"1"},
	})
	if err != nil {
		l.Logger.Error(err.Error())
	}

	// ---start---
	now := time.Now().Unix()
	accessExpire := l.svcCtx.Config.Auth.AccessExpire
	jwtToken, err := l.getJwtToken(l.svcCtx.Config.Auth.AccessSecret, now, l.svcCtx.Config.Auth.AccessExpire, userInfo.Id, userCount.Count)
	if err != nil {
		return nil, err
	}
	// ---end---

	return &types.LoginResponse{
		Code:    "200",
		Message: "success",
		JwtToken: types.JwtToken{
			AccessToken:  jwtToken,
			AccessExpire: now + accessExpire,
			RefreshAfter: now + accessExpire/2,
		},
	}, nil
}

func (l *LoginLogic) getJwtToken(secretKey string, iat, seconds, userId int64, count int32) (string, error) {
	claims := make(jwt.MapClaims)
	claims["exp"] = iat + seconds
	claims["iat"] = iat
	claims["userId"] = userId
	claims["count"] = count
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	return token.SignedString([]byte(secretKey))
}
